<template>
  <div>
    <el-dialog :title="lossForm.lossId?'修改报损信息':'新增报损'" :visible.sync="visible">
      <el-form :model="lossForm" label-width="80px" :rules="rules" ref="lossDom">
        <el-form-item label="时间" prop="date">
          <el-date-picker :editable="false" v-model="lossForm.date" value-format="yyyy-MM-dd" placeholder="报损日期"/>
        </el-form-item>
        <el-form-item label="商品" prop="goodsId">
          <el-select v-model="lossForm.goodsId" clearable filterable placeholder="请输入选择商品">
            <el-option v-for="item in goodsList" :key="item.goodsId" :label="item.name" :value="item.goodsId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="goodsAmount">
          <el-input v-model="lossForm.goodsAmount" clearable placeholder="商品数量"></el-input>
        </el-form-item>
        <el-form-item label="原因" prop="reason">
          <el-input v-model="lossForm.reason" clearable placeholder="报损原因"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="lossForm.remark" clearable placeholder="备注"></el-input>
        </el-form-item>
        <el-form-item label="照片列表">
          <el-upload :action="uploadUrl" :headers="uploadHeader" :list-type="'picture-card'" :before-upload="beforeUpload" :on-success="uploadSuccess" :file-list="imageList" ref="imageListRef">
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img :src="file.url" alt="" class="el-upload-list__item-thumbnail">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="showImageDetail(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="removeImage(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="imageListDialogVisible" append-to-body>
            <img :src="imageListDialogImgSrc" alt="" height="100%" width="100%">
          </el-dialog>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="lossForm.status">
            <el-radio :label="0">未处理</el-radio>
            <el-radio :label="1">已处理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button @click="visible=false">取消</el-button>
          <el-button type="primary" @click="submitInfo">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
const initInfo = {
  lossId: '',
  date: '',
  goodsAmount: '',
  reason: '',
  remark: '',
  status: 0,
  goodsId: '',
  imageNames: []
}

export default {
  name: 'LossAddOrUpdate',
  data () {
    return {
      visible: false,
      lossForm: {
        ...initInfo
      },
      rules: {
        date: [{ required: true, message: '时间不能为空', trigger: 'blur' }],
        goodsId: [{ required: true, message: '商品不能为空', trigger: 'blur' }],
        goodsAmount: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
        reason: [{ required: true, message: '原因不能为空', trigger: 'blur' }]
      },
      loading: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/upload',
      baseImageUrl: process.env.VUE_APP_BASE_API + '/img/',
      uploadHeader: {
        token: ''
      },
      dialogVisible: false,
      fileList: [],
      imageList: [],
      imageListDialogVisible: false,
      imageListDialogImgSrc: '',
      goodsList: []
    }
  },
  methods: {
    init (lossId) {
      /* 开启弹窗 */
      this.visible = true
      this.lossForm = { ...initInfo }

      /* 获取商品下拉框 */
      this.$http.get('/sales/select').then(data => {
        if (data.code === 0) {
          this.goodsList = data.data
        }
      })

      /* 判断lossId是否有值 */
      if (lossId) {
        /* 成立表示该次操作为修改，发送ajax请求获取信息 */
        this.$http.get('/loss/info/' + lossId).then(data => {
          if (data.code === 0) {
            this.lossForm = {
              ...data.data
            }
            /* 处理单张图片数据 */
            if (this.fileList.length > 0) {
              this.fileList.length = 0
            }
            this.fileList.push({ url: this.baseImageUrl + data.data.cover })
            /* 处理多张图片数据 */
            if (this.imageList.length > 0) {
              this.imageList.length = 0
            }
            this.imageList = this.lossForm.imageList.map(item => {
              return {
                name: item.imageUrl,
                url: this.baseImageUrl + item.imageUrl
              }
            })
            /* 处理提交的表单中的images */
            this.lossForm.imageNames = this.lossForm.imageList.map(item => item.imageUrl)
          } else {
            this.$message.error('数据加载失败，请重试！')
          }
        })
      }
    },
    submitInfo () {
      this.$refs.lossDom.validate(valid => {
        if (valid) {
          this.loading = this.$loading({ text: '加载中...' })
          this.$http.post('/loss/update', this.lossForm).then(data => {
            this.loading.close()
            if (data.code === 0) {
              this.$message({
                message: `${!this.lossForm.lossId ? '添加' : '修改'}成功`,
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('onCloseWin')
                }
              })
            } else {
              this.$alert('操作失败', { type: 'error' })
            }
          })
        }
      })
    },
    beforeUpload (file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isImg) {
        this.$message.error('文件格式不正确！')
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('文件大小不能超过5M')
      }
      return isImg && isLt5M
    },
    uploadSuccess (res) {
      if (res.code === 0) {
        this.lossForm.imageNames.push(res.data)
        this.imageList = this.lossForm.imageNames.map(item => {
          return {
            url: this.baseImageUrl + item,
            name: item
          }
        })
      }
    },
    showImageDetail (file) {
      this.imageListDialogVisible = true
      this.imageListDialogImgSrc = file.url
    },
    removeImage (file) {
      this.$confirm('确定删除该图片吗？').then(() => {
        this.$refs.imageListRef.handleRemove(file)
        for (let i = 0; i < this.lossForm.imageNames.length; i++) {
          if (this.lossForm.imageNames[i] === file.name) {
            this.lossForm.imageNames.splice(i, 1)
          }
        }
      })
    }
  },
  created () {
    this.uploadHeader.token = this.$cookies.get('token')
  }
}
</script>

<style scoped>

</style>
